import { Button, TextArea } from "tea-component";
import React, { useEffect, useState } from "react";
import { EditIcon } from "./EditIcon";
import "./group-accountecment.scss";
import { ConfirmDialog, ConfirmDialogRecordsType } from "./ConfirmDialog";
import { useDialogRef } from "../../../utils/react-use/useDialog";
import Toast from "../../../components/toast/Toast";
import { useDispatch, useSelector } from "react-redux";
import { updateUserInfo } from "../../../store/actions/user";

export const GroupAccountecment = (props: {
  accountecment: string;
  groupId: string;
  userIdentity: number;
  groupType: number;
  onRefresh: () => Promise<any>;
}): JSX.Element => {
  const { accountecment, groupId, userIdentity, groupType, onRefresh } = props;

  const [input, setInput] = useState(accountecment);
  const [isEdit, setIsEdit] = useState(false);
  const {userId,custominf} = useSelector((state: State.RootState) => state.userInfo);
  const dispatch = useDispatch();

  const dialogRef = useDialogRef<ConfirmDialogRecordsType>();

  const handleModify = async () => {
    // await modifyGroupInfo({
    //   groupId,
    //   modifyParams: {
    //     group_modify_info_param_notification: input,
    //   },
    // });
    const request = require('request')
      request.post(Toast.defaultser+'/api/app/group/editNotification',{
        headers: {
            Authorization: Toast.token,},           
        json: {
              imGroupId:groupId,notification:input,
            }
    },(error, res) => {
        if (error) {
            return
        }
        const data = res.body;
        if(data?.code == 200){
            dispatch(updateUserInfo({userId,custominf:{userNum:custominf.userNum,notification:input}}))
        }
    });
  };

  useEffect(() => {
    setInput(accountecment);
  }, [accountecment]);

  function handleInput() {
    dialogRef.current.open({
      description: `是否将群公告修改为`,
      modifyContent: input,
      onConfirm: handleModify,
    });
  }
  /**
   * 当前不是修改状态，才出现修改按钮
   * 对于公开群、聊天室和直播大群，只有群主或者管理员可以修改群简介。
   * 对于私有群，任何人可修改群简介。
   * 用户身份类型 memberRoleMap
   * 群类型  groupTypeMap
   */
  const canEdit = ([300, 400].includes(userIdentity));

  return (
    <>
      <div className="group-accountecment">
        <div className="group-accountecment--title">
          <span className="group-accountecment--title__text">群公告</span>
          {canEdit && <EditIcon onClick={() => setIsEdit(!isEdit)} />}
        </div>
        {isEdit ? (
                <div className="group-accountecment--box">
                  <TextArea className="group-accountecment--input"   value={input}   onChange={(value) => setInput(value)}/>
                  <Button type="weak"  onClick={handleInput}>保存</Button>
                </div>
        ) : (
          <div className="group-accountecment--info">{input || ""}</div>
        )}
      </div>
      <ConfirmDialog dialogRef={dialogRef} onSuccess={() => { onRefresh(); setIsEdit(false); }}/>
    </>
  );
};
